package com.boomsecret.juc.tools;

import java.util.concurrent.CountDownLatch;

/**
 * @author wangjinliang on 2019/1/23.
 */
public class CountDownLatchDemo {
    private static final int TEACHER_COUNT = 1;
    private static final int STUDENT_COUNT = 5;

    private static CountDownLatch teacher;
    private static CountDownLatch students;

    static {
        teacher = new CountDownLatch(TEACHER_COUNT);
        students = new CountDownLatch(STUDENT_COUNT);
    }

    public static void main(String[] args) {
        Thread[] threads = new Thread[STUDENT_COUNT];
        for (int index = 0; index < STUDENT_COUNT; index ++) {
            int temp = index;
            threads[index] = new Thread(() -> {
                students.countDown();
                System.out.println("index-" + temp + " prepare success");
                try {
                    teacher.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException("index-" + temp + " exception");
                }
                System.out.println("index-" + temp + " answer");
            });
            threads[index].start();
        }

        try {
            students.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("学生都准备好 老师开始宣布答题开始");
        teacher.countDown();

        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("答题结束");
    }
}
